import cryptoFramework from "@ohos.security.cryptoFramework"
import * as utils from './utils'

export class DataBlob implements cryptoFramework.DataBlob {
  data: Uint8Array;

  constructor(data: Uint8Array) {
    this.data = data;
  }
}

export enum CipherAlg {
  NONE = 0,
  RSA = 1,
  SM2 = 2,
  AES = 3,
  DES = 4,
  SM4 = 5,
}

export class Cipher {
  cipher: cryptoFramework.Cipher;

  constructor(alg: CipherAlg) {
    this.cipher = this.createCipher(alg);
  }

  encrypt(input: Uint8Array): void {
    this.cipher.update(new DataBlob(input), (err, data) => {
      if (err) {
        console.error("[update]: error code: " + err.code + ", message is: " + err.message);
      }
    });
  }

  getAlgName(alg: CipherAlg): string {
    let algName: string = null;
    switch (alg) {
      case CipherAlg.RSA:
        algName = 'RSA';
        break;
      case CipherAlg.SM2:
        algName = 'SM2';
        break;
      case CipherAlg.AES:
        algName = 'AES';
        break;
      case CipherAlg.DES:
        algName = 'DES';
        break;
      case CipherAlg.SM4:
        algName = 'SM4';
        break;
    }

    return algName;
  }

  private createCipher(alg: CipherAlg): cryptoFramework.Cipher {
    try {
      return cryptoFramework.createCipher(this.getAlgName(alg));
    } catch (error) {
      console.error("[createMd]: error code: " + error.code + ", message is: " + error.message);
      return null;
    }
  }
}